package com.heifeng.cloudshelf.network;


import android.text.TextUtils;
import android.util.Log;

import com.heifeng.cloudshelf.BuildConfig;
import com.heifeng.cloudshelf.utils.LogUtils;

import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;


/**
 * Created by Administrator on 2017/3/22.
 */
public class NetClient {
    private volatile static NetClient mInstance;
    private Retrofit mRetrofit;
    private static final int DEFAULT_TIMEOUT = 60; //默认超时时间60秒

    private static final String TAG = "Api";
    //    private static Context mContext;
//    private String mHost;
//    public static final int BASETYPE = 1;
//    public static final int TESTTYPE = 2;
    public static String token = "";
    public static String cliId = "";

    private NetClient() {
        OkHttpClient.Builder okBuilder = new OkHttpClient().newBuilder()
                .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
        if (BuildConfig.DEBUG) { //调试模式下开启打印信息
            //开启Log,打印网络请求信息
            HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(
                    message -> {
                        if (TextUtils.isEmpty(message)) return;
                        LogUtils.e(message);
                        Log.i(TAG, message);
                    });
            httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            okBuilder.addInterceptor(httpLoggingInterceptor);
        }
        Interceptor XRequestedWithInterceptor = chain -> {
            Request request = chain.request()
                    .newBuilder()
                    .addHeader("X-Requested-With", "XMLHttpRequest")
                    .build();
            return chain.proceed(request);
        };
        //请求头设置key=Authorization，value=Bearer+（空格）+token的值
        //    private String authorizationValue = "";
        //String authorizationValue = "Bearer " + "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImM3NWIwNjk2ODVlOTAzNDA2NDcyN2U0MGYwMzZiMmI5ZWJjMGJlYWQ5YTM3ZmYyZWJkOGQyNzEzODEyMzA4MjYyOWNlY2E4NzE4MjBlMjZmIn0.eyJhdWQiOiIyIiwianRpIjoiYzc1YjA2OTY4NWU5MDM0MDY0NzI3ZTQwZjAzNmIyYjllYmMwYmVhZDlhMzdmZjJlYmQ4ZDI3MTM4MTIzMDgyNjI5Y2VjYTg3MTgyMGUyNmYiLCJpYXQiOjE1NjAxNTA3MjYsIm5iZiI6MTU2MDE1MDcyNiwiZXhwIjoxNTYzNzUwNzI2LCJzdWIiOiI5Iiwic2NvcGVzIjpbIioiXX0.XbJZt3ZvbGk4II3HBVN_GvL3g9LQfxQ1eF41T4gPW78HAWcIyTybrSed7CuxyA9YOv7FDtLdWPL-BN9F_Q61_WpAizFR-csQI1OVMBoWqALgqjQuV4QslAseWJJ9rTv26p8rjkSDkAdxCqB-zCcLOqdeHCeR1o8WZwbPMc-VAuyAYY4uzkUoxHBb9oeaFkGyAbmP8MiiYk7ikuGAFhlWqqtv1woBBHLVVAVuLpg_l84HKIyr80u63wl6Qv1FPnUrij1ROgdZD_RJLsE5OoW90tjkYky8SBYiXJ2MU1SyDdRF_9fu521DT1sBj11UlWfDe0xcVAudoeIGuUSr6ojtJ3EBstfDJnQAUTwjEve9mcAz4pf2hRXkYFKH7Zd-VeAXkgckvq7DBXWIeqMSlnePBY7lLKqxFBYw_Xs51wvndxFivngJLGZwd_W0ch_2wrCOKypGp00MdspEsQyv9GK-P6zYvk0DnqCGNgpoqmGi07YRmXDXfmReY-GSZlYpF8AvP7R5o7_eufsQZKTGQMoa4CAbX620Dnv9bV0Gnq66VStv95PZhNbwxHNQyiwMqof7H_YxKQPqmjSEBeVYyvm16cMfVegWK6jcfICe2I1V6arD196g8WsDNZZfEFgAVTkMsVVfDRLaJIl2dMcgPbuplMUSsQDn2Uvytjt8KKbYdNk";
        //            Request request = chain.request()
        //                    .newBuilder()
        //                    .addHeader("Authorization", authorizationValue)
        //                    .build();
        //            builder.addHeader("Content-Type","application/json;charset=UTF-8");
        //change in 2019.9.19
        //builder.addHeader("cliId","291b19b0dddcbb51bd65706ca3d7b613");
        //builder.addHeader("token","aca0805534da491db6bd01dc848bf2b8");
        Interceptor authorizationInterceptor = chain -> {
//            Request request = chain.request()
//                    .newBuilder()
//                    .addHeader("Authorization", authorizationValue)
//                    .build();
            Request.Builder rBuilder = chain.request().newBuilder();
//            builder.addHeader("Content-Type","application/json;charset=UTF-8");
            rBuilder.addHeader("Content-Type", "application/x-www-form-urlencoded");

            //change in 2019.9.19
            //builder.addHeader("cliId","291b19b0dddcbb51bd65706ca3d7b613");
            //builder.addHeader("token","aca0805534da491db6bd01dc848bf2b8");
            if (!TextUtils.isEmpty(NetClient.cliId)) {
                rBuilder.addHeader("cliId", NetClient.cliId);
                Log.e("api", "cliId:" + NetClient.cliId);
            }
            if (!TextUtils.isEmpty(NetClient.token)) {
                rBuilder.addHeader("token", NetClient.token);
                Log.e("api", "token:" + NetClient.token);
            }
            rBuilder.addHeader("Accept", "application/json");
            return chain.proceed(rBuilder.build());
        };
        okBuilder.addInterceptor(XRequestedWithInterceptor).addInterceptor(authorizationInterceptor);
        OkHttpClient httpClient = okBuilder.build();
        mRetrofit = new Retrofit.Builder()
                .baseUrl(BuildConfig.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(httpClient)
                .build();
    }

    public static NetClient getInstance() {
//        WeakReference<Context> contextWeakReference = new WeakReference<Context>(context);
//        mContext = contextWeakReference.get();
        if (mInstance == null) {
            synchronized (NetClient.class) {
                if (mInstance == null) {
                    mInstance = new NetClient();
                }
            }
        }
        return mInstance;
    }

    //根据hostType获取baseUrl
//    public String getHost(int hostType) {
//        String host = null;
//        switch (hostType) {
//            case BASETYPE:
//                host = HTTPConstants.baseUrl;
//                break;
//            case TESTTYPE:
//                host = HTTPConstants.testUrl;
//                break;
//        }
//        return host;
//    }

    public NetApi getNetApi() {
        return mRetrofit.create(NetApi.class);
        //设置缓存
//        File httpCacheDirectory = new File(mContext.getCacheDir(), "cache_responses");
//        Cache cache = null;
//        try {
//            cache = new Cache(httpCacheDirectory, 10 * 1024 * 1024);
//        } catch (Exception e) {
//            Log.e("OKHttp", "Could not create http cache", e);
//        }
//        Log.d("Api", "------------>authorizationValue=" + authorizationValue);

        //开启Log,打印网络请求信息
//        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(
//                message -> {
//                    if (TextUtils.isEmpty(message)) return;
//                    LogUtils.e(message);
//                    Log.i(TAG, message);
//                });
//        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
//
//        OkHttpClient okHttpClient = new OkHttpClient.Builder()
////                .cache(cache)
//                .readTimeout(60, TimeUnit.SECONDS)
//                .connectTimeout(60, TimeUnit.SECONDS)
//                .addInterceptor(httpLoggingInterceptor)
////                .addInterceptor(interceptorToken)
//                .addInterceptor(XRequestedWithInterceptor)
//                .addInterceptor(authorizationInterceptor)
//                .build();
//
////        builder.addInterceptor(new RequestHeaderInterceptor());
//        mHost = getHost(BASETYPE);
//        Retrofit retrofit = new Retrofit.Builder()
//                .baseUrl(mHost)
//                .addConverterFactory(GsonConverterFactory.create())
//                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
//                .client(okHttpClient)
//                .build();
//        return retrofit.create(NetApi.class);
    }

//    public NetApi getNetApi1() {
//        //设置缓存
////        File httpCacheDirectory = new File(mContext.getCacheDir(), "cache_responses");
////        Cache cache = null;
////        try {
////            cache = new Cache(httpCacheDirectory, 10 * 1024 * 1024);
////        } catch (Exception e) {
////            Log.e("OKHttp", "Could not create http cache", e);
////        }
////        Log.d("Api", "------------>authorizationValue=" + authorizationValue);
//
//        //开启Log,打印网络请求信息
//        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(
//                message -> {
//                    if (TextUtils.isEmpty(message)) return;
//                    LogUtils.e(message);
//                    Log.i(TAG, message);
//                });
//        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
//
//        OkHttpClient okHttpClient = new OkHttpClient.Builder()
////                .cache(cache)
//                .readTimeout(60, TimeUnit.SECONDS)
//                .connectTimeout(60, TimeUnit.SECONDS)
//                .addInterceptor(httpLoggingInterceptor)
////                .addInterceptor(interceptorToken)
//                .addInterceptor(XRequestedWithInterceptor)
//                .addInterceptor(authorizationInterceptor)
//                .build();
//
////        builder.addInterceptor(new RequestHeaderInterceptor());
////        mHost = getHost(TESTTYPE);
//        Retrofit retrofit = new Retrofit.Builder()
//                .baseUrl("https://admintest.holike.com")
//                .addConverterFactory(GsonConverterFactory.create())
//                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
//                .client(okHttpClient)
//                .build();
//        return retrofit.create(NetApi.class);
//    }

    //带Authorization
//    public NetApi getNetApi2() {
//        //设置缓存
////        File httpCacheDirectory = new File(mContext.getCacheDir(), "cache_responses");
////        Cache cache = null;
////        try {
////            cache = new Cache(httpCacheDirectory, 10 * 1024 * 1024);
////        } catch (Exception e) {
////            Log.e("OKHttp", "Could not create http cache", e);
////        }
//        Log.d("Api", "------------>authorizationValue=" + authorizationValue);
//
//        //开启Log,打印网络请求信息
//        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(
//                new HttpLoggingInterceptor.Logger() {
//                    @Override
//                    public void log(String message) {
//                        if (TextUtils.isEmpty(message)) return;
//                        Log.i(TAG, message);
//                    }
//                });
//        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
//
//        OkHttpClient okHttpClient = new OkHttpClient.Builder()
////                .cache(cache)
//                .readTimeout(60, TimeUnit.SECONDS)
//                .connectTimeout(60, TimeUnit.SECONDS)
//                .addInterceptor(httpLoggingInterceptor)
////                .addInterceptor(interceptorToken)
//                .addInterceptor(XRequestedWithInterceptor)
//                .addInterceptor(authorizationInterceptor)
//                .build();
//
//        mHost = getHost(BASETYPE);
//        Retrofit retrofit = new Retrofit.Builder()
//                .baseUrl(mHost)
//                .addConverterFactory(GsonConverterFactory.create())
//                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
//                .client(okHttpClient)
//                .build();
//        return retrofit.create(NetApi.class);
//    }


    /*
     * 拦截器，保存缓存的方法
     */
//    private int netGet = 0;
//    private int nonetGet = 0;
//    Interceptor interceptorCache = new Interceptor() {
//        @Override
//        public Response intercept(Chain chain) throws IOException {
//            Request request = chain.request();
//
//            if (isNetworkConnected()) {//有网时
//                Response response = chain.proceed(request);
//                String cacheControl = request.cacheControl().toString();
//                switch (netGet) {
//                    case 0://总获取实时信息
//                        return response.newBuilder()
//                                .removeHeader("Pragma")
//                                .removeHeader("Cache-Control")
//                                .header("Cache-Control", "public, max-age=" + 0)
//                                .build();
//                    case 1://t（s）之后获取实时信息--此处是60s
//                        return response.newBuilder()
//                                .removeHeader("Pragma")
//                                .removeHeader("Cache-Control")
//                                .header("Cache-Control", "public, max-age=" + cacheTime)
//                                .build();
//                }
//                return null;
//            } else {//无网时
//                switch (nonetGet) {
//                    case 0://无网时一直请求有网请求好的缓存数据，不设置过期时间
//                        request = request.newBuilder()
//                                .cacheControl(CacheControl.FORCE_CACHE)//此处不设置过期时间
//                                .build();
//                        break;
//                    case 1://此处设置过期时间为t(s);t（s）之前获取在线时缓存的信息(此处t=20)，t（s）之后就不获取了
//                        request = request.newBuilder()
//                                .cacheControl(FORCE_CACHE1)//此处设置了t秒---修改了系统方法
//                                .build();
//                        break;
//                }
//
//                Response response = chain.proceed(request);
//                //下面注释的部分设置也没有效果，因为在上面已经设置了
//                return response.newBuilder()
//                        .header("Cache-Control", "public, only-if-cached")
//                        .removeHeader("Pragma")
//                        .build();
//            }
//
//        }
//    };
//    private int cacheTime = 60;
//    //这是设置在多长时间范围内获取缓存里面
//    public CacheControl FORCE_CACHE1 = new CacheControl.Builder()
//            .onlyIfCached()
//            .maxStale(cacheTime, TimeUnit.SECONDS)//CacheControl.FORCE_CACHE--是int型最大值
//            .build();

    /*
     * 检测网络是否可用
     *
     * @return
     */
//    public boolean isNetworkConnected() {
//        ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
//        NetworkInfo ni = cm.getActiveNetworkInfo();
//        return ni != null && ni.isConnectedOrConnecting();
//    }

}
